<?php

namespace App\Repository;

use App\Models\Menu as model;
use Illuminate\Support\Facades\Cache;
use App\Repository\RoleRepository;
use Illuminate\Support\Facades\DB;

class MenuRepository extends  BaseRepository
{
  private $model;
  private $role;
  public function __construct(model $model, RoleRepository $RoleRepository)
  {
    $this->model = $model;
    $this->role = $RoleRepository;
    parent::__construct();
  }
  //列表
  public function index($where)
  {
    $cron = $where;
    $cron['order'] = ['orderby' => 'menu_id', 'orderdir' => 'desc'];
    // $cron['where'] = $where;
    // var_dump($cron,111111111);
    $data = $this->search($this->model, $cron, 1, 9000000);
    if (!empty($data['data'])) {
      $data['data'] = usfirstArr($data['data']);
    }
    return $data;
  }
  //添加
  public function add($data)
  {
    //必填 字段
    $mustField = [
      'menu_name',
    ];
    $optionalFields = $this->model->getTableField();
    $msgField = [
      'menu_name' => '名称不能为空'
    ];
    $insertData  = $this->getRealData($data, $mustField, $optionalFields, $msgField);
    if (!empty($insertData) && is_string($insertData)) {
      //返回错误参数
      return $this->returnMsg(
        2,
        $insertData
      );
    }
    $insertData['create_time'] = date('Y-m-d H:i:s');
    $res = $this->model->insert($insertData);
    if ($res) {
      $this->clearCache(1);
      return $this->returnMsg(200, '添加成功');
    }
    return $this->returnMsg(1, '添加失败');
  }
  //删除
  public function del($where)
  {
    $flag = true;
    $msg = '未知错误';
    $code = 1;
    if (empty($where)) {
      $flag = false;
      $msg = '删除条件不能为空';
      $code = 2;
    }
    if ($flag) {
      $res = $this->model->where($where)->get();
      if (!$res) {
        $flag = false;
        $msg = '未查询到数据';
        $code = 3;
      }
    }
    if ($flag) {
      $del = $this->model->where($where)->delete();
      if ($del) {
        $this->clearCache(1);
        $msg = '删除成功';
        $code = 200;
      }
    }
    return $this->returnMsg($code, $msg);
  }
  //修改
  public function edit($where, $data, $isMust = false)
  {
    $this->clearCache(1);
    if (empty($where)) {
      return $this->returnMsg(1, '条件不能为空');
    }
    if (empty($data)) {
      return $this->returnMsg(2, '修改参数不能为空');
    }
    //过滤字段
    //过滤字段
    $optionalFields = $this->model->getTableField();
    $field  = $this->getRealData($data, [], $optionalFields, []);
    //先查询是否存在
    $field['update_time'] = date('Y-m-d H:i:s');
    $res = $this->model->where($where)->update($field);
    if ($isMust && $res) {
      return $this->returnMsg(200, '修改成功');
    }
    if (!$isMust) {
      return $this->returnMsg(200, '修改成功');
    }
    return $this->returnMsg(3, '请重新修改');
  }
  public function sel($where = [], $roleId = 1)
  {
    // $cache = Cache::get($roleId.'menu_list');
    //权限查询
    // var_dump($roleId);
    // DB::enableQueryLog();
    if (is_array($roleId)) {
      $res = $this->role->getMore([], ['name' => 'role_id', 'value' => $roleId]);
      // 这个地方处理过来的就是多条
      // 将多条数据 合并成一条数据
    }
    if (is_string($roleId)) {
      $res = $this->role->getOne(['role_id' => $roleId]);
    }
    // var_dump($res);
    // $sql = DB::getQueryLog();
    // var_dump($sql);
    $exIdsArr = [];
    $inIdsArr = [];
    if (empty($res[0])) {
      if (!empty($res->ex_ids)) {
        $exIdsArr = explode(',', $res->ex_ids);
      }
      if (!empty($res->in_ids)) {
        $inIdsArr = explode(',', $res->in_ids);
      }
    }
    if (!empty($res[0])) {
      foreach ($res as $key => $v) {
        if (!empty($v->ex_ids)) {
          $exIdsArrA = explode(',', $v->ex_ids);
        }
        if (!empty($v->in_ids)) {
          $inIdsArrA = explode(',', $v->in_ids);
        }
        if (!empty($exIdsArrA)) {
          $exIdsArr = array_merge($exIdsArrA, $exIdsArr);
        }
        if (!empty($inIdsArrA)) {
          $inIdsArr = array_merge($inIdsArrA, $inIdsArr);
        }
      }
    }
    // var_dump($inIdsArr, 3333333333);
    // var_dump($exIdsArr, 444444444444);

    // var_dump($exIdsArr,4444444444);
    if (!empty($cache)) {
      // return json_decode($cache, true);
    }
    $res = $this->getSel($where, $exIdsArr, $inIdsArr);
    // Cache::forever($roleId . 'menu_list', json_encode($res));
    // var_dump($res,55555555555);
    return $res;
  }
  //查看  存入缓存
  public function getSel($where = [], $exIdsArr = [], $inIdsArr = [])
  {

    //查询菜单列表
    if (empty($where)) {
      $where  = [
        'parent_id' => 0,
        'status' => 0
        // 'hasFlag' => 1,
      ];
    }
    $field = [
      'path',
      'menu_name as name',
      'perms',
      'component',
      'visible',
      'menu_id',
      'icon',
      'parent_id',
      'menu_type',
      'is_frame'
    ];
    $res = $this->model->where($where)->orderBy('order_num', 'desc')->orderBy('menu_id', 'asc')->get($field)->toArray();
    $returnData = [];
    if (!empty($res)) {
      foreach ($res as $key => &$v) {
        if (!empty($exIdsArr)) {
          if (in_array($v['menu_id'], $exIdsArr)) {
            unset($res[$key]);
            continue;
          }
        }
        if (!empty($inIdsArr)) {
          if (!empty($inIdsArr[0]) && $inIdsArr[0] != '*'  && !in_array($v['menu_id'], $inIdsArr)) {
            unset($res[$key]);
            continue;
          }
        }
        // 按钮数据转换
        $v['meta'] = [
          'title' => $v['name'],
          'icon' => $v['icon'],
          'noCache' => false,
        ];
        $v['name'] = ucwords($v['path']);
        if (empty($v['visible']) || $v['visible'] != 1) {
          $v['hidden'] = false;
        } else {
          $v['hidden'] = true;
        }
        if ($v['parent_id'] == 0) {
          $v['redirect'] = 'noRedirect';
          $v['alwaysShow'] = true;
          $v['path'] = '/' . $v['path'];
        }
        if ($v['menu_type'] == 'C' && $v['is_frame'] == 1) {
          $v['redirect'] = 'noRedirect';
          // $v['alwaysShow'] = true;
        }
        if ($v['is_frame'] != 1) {
          $v['meta']['link'] = $v['path'];
          $v['alwaysShow'] = false;
        }

        $where = [];
        $where[] = ['parent_id', '=', $v['menu_id']];
        $where[] = ['status', '=', 0];
        $where[] = ['menu_type', '=', 'C'];
        $data = $this->getSel($where, $exIdsArr, $inIdsArr);
        // var_dump($data);
        if (!empty($data)) {
          $v['children'] = $data;
        } else {
          if (isset($v['alwaysShow'])) {
            unset($v['alwaysShow']);
          }
        }
        $returnData[] = $v;
      }
    }
    return $returnData;
  }
  //列表查询
  public function lists($where = [], $page = 1, $limit = 10)
  {
    $res = $this->search($this->model, $where, $page, $limit);

    return $res;
  }
  //只获取一级的
  public function getOneTrue($where = [], $field = [], $i = 0, $num = 1, $roleId = 0)
  {
    //查询菜单列表
    if (empty($where)) {
      $where  = [
        'parent_id' => 0,
        'status' => 0,
      ];
    }
    if (empty($field)) {
      $field = [
        'menu_id as id',
        'menu_name as label'
      ];
    }
    $exIdsArr = [];
    $inIdsArr = [];
    if (!empty($roleId)) {
      $resRole = $this->role->getOne(['role_id' => $roleId]);

      if (!empty($resRole->ex_ids)) {
        $exIdsArr = explode(',', $resRole->ex_ids);
      }
      if (!empty($resRole->in_ids)) {
        $inIdsArr = explode(',', $resRole->in_ids);
      }
      // var_dump($inIdsArr);
    }

    $res = $this->model->where($where)->get($field)->toArray();
    $return = [];
    $j = 0;
    $i++;
    if (!empty($res) && $i < $num) {
      foreach ($res as $key => $v) {
        if ((empty($inIdsArr) || !in_array($v['id'], $inIdsArr))  && $roleId != 1) {
          // var_dump($v['id']);
          // var_dump($inIdsArr);
          // var_dump($res[$key]);
          unset($res[$key]);
          continue;
        }
        $return[$j] = $v;
        $TwoWhere = [
          'parent_id' => $v['id'],
          'status' => 0,
        ];

        $data = $this->getOneTrue($TwoWhere, [], $i, $num, $roleId);
        $return[$j]['children'] = (array)$data;
        $j++;
        // if (empty($data)) {
        //   var_dump($data);
        // }
      }
    }
    // var_dump($res);
    return $return;
  }

  //清除缓存 当用户添加,删除或者修改的时候
  public function clearCache($role = 0)
  {
    // Cache::flush();
    //清除菜单的缓存
    $rule = DB::table('role')->get();
    if (!empty($rule)) {
      foreach ($rule as $key => $v) {
        // Cache::forget($v->id.'menu_list');
      }
    }
  }
  public function getOne($where)
  {
    return $this->model->where($where)->first();
  }
}
